package com.liuh.appsys.controller.developer;

import java.io.File;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

import org.apache.commons.io.FilenameUtils;
import org.apache.log4j.Logger;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import com.liuh.appsys.pojo.AppCategory;
import com.liuh.appsys.pojo.AppInfo;
import com.liuh.appsys.pojo.DataDictionary;
import com.liuh.appsys.pojo.DevUser;
import com.liuh.appsys.service.AppCateService;
import com.liuh.appsys.service.AppInfoService;
import com.liuh.appsys.service.DataDictionaryService;
import com.liuh.appsys.tools.MyConstants;
import com.liuh.appsys.tools.PageSupport;

/**
 * @note app info
 * @author liuh
 * */
@Controller
@RequestMapping("/dev/app")
public class AppInfoController {
	
	private Logger logger = Logger.getLogger(AppInfoController.class);

	@Resource
	AppInfoService infoService;
	
	@Resource
	DataDictionaryService dictionaryService;
	
	@Resource
	AppCateService appCateService;
	
	/**
	 * @note appInfo list
	 * @author liuh
	 * */
	@RequestMapping("/appList")
	public String appInfo(AppInfo appInfo,@RequestParam(value="pageIndex",required=false)Integer currentPageNo,Model model) {
		//当前页号
		currentPageNo=currentPageNo==null?1:currentPageNo;
		//组合条件 分页查询
		PageSupport page=infoService.getAppInfos(appInfo,currentPageNo,MyConstants.pageSize);
		//
		List<DataDictionary> status=dictionaryService.getDictionaryByType("APP_STATUS");
		List<DataDictionary> flatForm=dictionaryService.getDictionaryByType("APP_FLATFORM");
		//分类数据
		List<AppCategory> cate1=appCateService.getAppCateByCateId(0L);
		List<AppCategory> cate2=appCateService.getAppCateByCateId(appInfo.getCategoryLevel1());
		List<AppCategory> cate3=appCateService.getAppCateByCateId(appInfo.getCategoryLevel2());
		//
		model.addAttribute("appInfoList",page.getData());
		model.addAttribute("pages",page);
		model.addAttribute("statusList",status);
		model.addAttribute("flatFormList", flatForm);
		model.addAttribute("categoryLevel1List",cate1);
		model.addAttribute("categoryLevel2List", cate2);
		model.addAttribute("categoryLevel3List",cate3);
		//
		model.addAttribute("appInfo",appInfo);
		return "/developer/appinfolist";
	}
	
	/**
	 * @note app 分类 json
	 * @author liuh
	 * */
	@ResponseBody
	@RequestMapping("/appCate")
	public List<AppCategory> appCateJson(long pid) {
		List<AppCategory> cate=appCateService.getAppCateByCateId(pid);
		return cate;
	}
	
	/**
	 * @note app 所属平台 json
	 * @author liuh
	 * */
	@ResponseBody
	@RequestMapping("/appFlat")
	public List<DataDictionary> appFlatJson(String appFlat) {
		List<DataDictionary> flatForm=dictionaryService.getDictionaryByType(appFlat);
		return flatForm;
	}
	
	/**
	 * 增加app信息（跳转到新增appinfo页面）
	 * @param appInfo
	 * @author liuh
	 */
	@RequestMapping(value="/appinfoadd",method=RequestMethod.GET)
	public String add(@ModelAttribute("appInfo") AppInfo appInfo){
		return "developer/appinfoadd";
	}
	
	/**
	 * @note 验证apk名称
	 * @author liuh
	 * */
	@ResponseBody
	@RequestMapping("/apkexist")
	public Map<String, String> apkexist(@RequestParam(required=false) String APKName) {
		Map<String, String> map=new HashMap<String, String>();
		String result="empty";
		if(!StringUtils.isEmpty(APKName)) {
			result=infoService.isExistApkName(APKName);
		}
		map.put("APKName", result);
		return map;
	}
	
	/**
	 * 保存新增appInfo（主表）的数据
	 * @param appInfo
	 * @param session
	 * @return
	 */
	@RequestMapping(value="/appinfoaddsave",method=RequestMethod.POST)
	public String addSave(AppInfo appInfo,HttpSession session,HttpServletRequest request,
			@RequestParam("a_logoPicPath")MultipartFile attach){		
		
		String logoPicPath =  null;
		String logoLocPath =  null;
		if(!attach.isEmpty()){
			String path = request.getSession().getServletContext().getRealPath("statics"+java.io.File.separator+"uploadfiles");
			logger.info("uploadFile path: " + path);
			String oldFileName = attach.getOriginalFilename();//原文件名
			String prefix = FilenameUtils.getExtension(oldFileName);//原文件后缀
			int filesize = 500000;
			if(attach.getSize() > filesize){//上传大小不得超过 50k
				request.setAttribute("fileUploadError", MyConstants.FILEUPLOAD_ERROR_4);
				return "developer/appinfoadd";
            }else if(prefix.equalsIgnoreCase("jpg") || prefix.equalsIgnoreCase("png") 
			   ||prefix.equalsIgnoreCase("jepg") || prefix.equalsIgnoreCase("pneg")){//上传图片格式
				 String fileName = appInfo.getAPKName() + ".jpg";//上传LOGO图片命名:apk名称.apk
				 File targetFile = new File(path,fileName);
				 if(!targetFile.exists()){
					 targetFile.mkdirs();
				 }
				 try {
					attach.transferTo(targetFile);
				} catch (Exception e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
					request.setAttribute("fileUploadError", MyConstants.FILEUPLOAD_ERROR_2);
					return "developer/appinfoadd";
				} 
				 logoPicPath = request.getContextPath()+"/statics/uploadfiles/"+fileName;
				 logoLocPath = path+File.separator+fileName;
			}else{
				request.setAttribute("fileUploadError", MyConstants.FILEUPLOAD_ERROR_3);
				return "developer/appinfoadd";
			}
		}
		appInfo.setCreatedBy(((DevUser)session.getAttribute(MyConstants.DEV_USER_SESSION)).getId());
		appInfo.setCreationDate(new Date());
		appInfo.setLogoPicPath(logoPicPath);
		appInfo.setLogoLocPath(logoLocPath);
		appInfo.setDevId(((DevUser)session.getAttribute(MyConstants.DEV_USER_SESSION)).getId());
		appInfo.setStatus(1L);
		try {
			if(infoService.add(appInfo)){
				return "redirect:/dev/app/appList";
			}
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return "developer/appinfoadd";
	}
	
}
